package com.wanfangdata.demo;

import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.client.RestTemplate;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Base64;
import java.util.UUID;

@Controller
@RequestMapping("/demo")
public class FulltextController {
    @RequestMapping("/fulltext")
    public void gateway(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String url = "https://api.wanfangdata.com.cn/openwanfang/fulltextDownload";
        String query = "timestamp=" + System.currentTimeMillis() + "&docId=Periodical_fjzlgl202005184";
        //TODO:
        String appSecret = "应用高级信息APPSecret";
        String md5 = DigestUtils.md5DigestAsHex((query.replaceAll("=", "").replaceAll("&", "") + appSecret).getBytes()).toLowerCase();

        RestTemplate rest = new RestTemplate();
        HttpHeaders header = new HttpHeaders();
        //TODO:
        String appKey = "应用高级信息APPKey";
        header.add("X-Ca-AppKey", appKey);
        header.add("X-Ca-Signature", md5);
        System.out.println(url + "?" + query);
        ResponseEntity<Resource> entity = rest.exchange(url + "?" + query, HttpMethod.GET,
                new HttpEntity<String>(header), Resource.class);


        System.out.println("httpStatus:" + entity.getStatusCode());


        MediaType contentType = entity.getHeaders().getContentType();

        try (InputStream inputStream = entity.getBody().getInputStream()) {
            response.setContentType(contentType.toString());
            File file = Paths.get(System.getProperty("user.dir"), UUID.randomUUID().toString() + ".b64").toFile();
            System.out.println(file);
            try (FileOutputStream stream = new FileOutputStream(file)) {
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(buffer)) != -1) {
                    if (len != buffer.length) {
                        byte[] copy = Arrays.copyOf(buffer, len);
                        stream.write(copy);
                    } else {
                        stream.write(buffer);
                    }
                }
            }
            //error
            if (contentType == null || !contentType.toString().toLowerCase().contains("pdf")) {
                byte[] bytes = Files.readAllBytes(file.toPath());
                try (ServletOutputStream stream = response.getOutputStream()) {
                    stream.write(bytes);
                }
                return;
            }
            Base64.Decoder decoder = Base64.getDecoder();
            try (FileInputStream in = new FileInputStream(file); ServletOutputStream stream = response.getOutputStream()) {
                byte[] buffer = new byte[4 * 1024];
                int len = 0;
                while ((len = in.read(buffer)) != -1) {
                    if (len != buffer.length) {
                        byte[] copy = Arrays.copyOf(buffer, len);
                        stream.write(decoder.decode(copy));
                    } else {
                        stream.write(decoder.decode(buffer));
                    }
                }
            } finally {
                file.delete();
            }
            response.addHeader("Content-Disposition", "online;filename=" + new String("test.pdf".getBytes(), StandardCharsets.ISO_8859_1));
        }
    }
}
